import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/services.dart';
// import 'package:flutter_hms_scan_kit/flutter_hms_scan_kit.dart';
// import 'package:flutter_hms_scan_kit/scan_result.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class ApiService {
  static const String baseUrl = 'http://aiotcomm.com.cn:50210';

  // 登录接口（不需要token）
  static Future<Map<String, dynamic>> login(
      String username, String password) async {
    final url = Uri.parse('$baseUrl/auth/login');

    try {
      final response = await http.post(
        url,
        headers: {'Content-Type': 'application/json'},
        body: json.encode({
          'username': username,
          'password': password,
        }),
      );
      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('登录失败: ${response.statusCode} - ${response.body}');
      }
    } catch (e) {
      throw Exception('网络请求失败: $e');
    }
  }

  // 带token的通用GET请求
  static Future<Map<String, dynamic>> get(String endpoint, String token) async {
    final url = Uri.parse('$baseUrl/$endpoint');

    try {
      final response = await http.get(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token', // 添加token到请求头
        },
      );

      return _handleResponse(response);
    } catch (e) {
      throw Exception('GET请求失败: $e');
    }
  }

  // 带token的通用POST请求
  static Future<Map<String, dynamic>> post(String endpoint, String token,
      {dynamic data}) async {
    final url = Uri.parse('$baseUrl/$endpoint');

    try {
      final response = await http.post(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token', // 添加token到请求头
        },
        body: data != null ? json.encode(data) : null,
      );

      return _handleResponse(response);
    } catch (e) {
      throw Exception('POST请求失败: $e');
    }
  }

  // 带token的通用PUT请求
  static Future<Map<String, dynamic>> put(String endpoint, String token,
      {dynamic data}) async {
    final url = Uri.parse('$baseUrl/$endpoint');

    try {
      final response = await http.put(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token', // 添加token到请求头
        },
        body: data != null ? json.encode(data) : null,
      );

      return _handleResponse(response);
    } catch (e) {
      throw Exception('PUT请求失败: $e');
    }
  }

  // 带token的通用DELETE请求
  static Future<Map<String, dynamic>> delete(
      String endpoint, String token) async {
    final url = Uri.parse('$baseUrl/$endpoint');

    try {
      final response = await http.delete(
        url,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token', // 添加token到请求头
        },
      );

      return _handleResponse(response);
    } catch (e) {
      throw Exception('DELETE请求失败: $e');
    }
  }

  // 统一处理响应
  static Map<String, dynamic> _handleResponse(http.Response response) {
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // 强制使用 UTF-8 解码响应体（解决编码不一致问题）
      final responseBody = utf8.decode(response.bodyBytes);
      if (responseBody.isEmpty) {
        return {'status': response.statusCode};
      }
      return json.decode(responseBody); // 使用解码后的字符串解析
    } else if (response.statusCode == 401) {
      throw Exception('身份验证失败，请重新登录');
    } else {
      throw Exception(
          '请求失败: ${response.statusCode} - ${utf8.decode(response.bodyBytes)}');
    }
  }

  // 保留原方法
  static String getOtherApiUrl(String endpoint) {
    return '$baseUrl/$endpoint';
  }
}

// 应用状态管理
class MyAppState extends ChangeNotifier {
  var currentOperation = Operation.none;
  bool _isLoggedIn = false;
  String? _username;
  String? _token;

  bool get isLoggedIn => _isLoggedIn;
  String? get username => _username;
  String? get token => _token;

  void startPicking() {
    currentOperation = Operation.picking;
    notifyListeners();
  }

  void startRestocking() {
    currentOperation = Operation.restocking;
    notifyListeners();
  }

  void resetOperation() {
    currentOperation = Operation.none;
    notifyListeners();
  }

  void loginSuccess(String username, String token) {
    _isLoggedIn = true;
    _username = username;
    _token = token;
    notifyListeners();
  }

  void logout() {
    _isLoggedIn = false;
    _username = null;
    _token = null;
    favoriteItems.clear();
    notifyListeners();
  }

  var favoriteItems = <String>[];

  void addToFavorites(String itemId) {
    if (!favoriteItems.contains(itemId)) {
      favoriteItems.add(itemId);
      notifyListeners();
    }
  }

  void removeFromFavorites(String itemId) {
    favoriteItems.remove(itemId);
    notifyListeners();
  }
}

enum Operation { none, picking, restocking }

// 主应用
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => MyAppState(),
      child: MaterialApp(
        title: 'GOODS',
        theme: ThemeData(
          useMaterial3: true,
          colorScheme: ColorScheme.fromSeed(
              seedColor: const Color.fromARGB(255, 12, 113, 255)),
        ),
        home: Consumer<MyAppState>(
          builder: (context, state, child) {
            return state.isLoggedIn ? MyHomePage() : const LoginPage();
          },
        ),
        routes: {
          '/home': (context) => MyHomePage(),
          '/login': (context) => const LoginPage(),
          '/picking': (context) => const PickingPage(),
          '/restocking': (context) => const RestockingPage(),
        },
      ),
    );
  }
}

// 登录页面
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isLoading = false;
  bool _obscurePassword = true;

  Future<void> _submitForm() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });

      try {
        final result = await ApiService.login(
          _usernameController.text.trim(),
          _passwordController.text.trim(),
        );

        if (result['status'] == 200) {
          Provider.of<MyAppState>(context, listen: false).loginSuccess(
            _usernameController.text.trim(),
            result['token'],
          );

          if (mounted) {
            Navigator.pushReplacementNamed(context, '/home');
          }
        } else {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('登录失败')),
            );
          }
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(e.toString())),
          );
        }
      } finally {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const SizedBox(height: 80),
              const Center(
                child: Text(
                  '智能星闪拣货系统',
                  style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.bold,
                    color: Color.fromARGB(255, 12, 113, 255),
                  ),
                ),
              ),
              const SizedBox(height: 60),
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _usernameController,
                      decoration: InputDecoration(
                        labelText: '用户名',
                        prefixIcon: const Icon(Icons.person),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        filled: true,
                        fillColor: Colors.grey[50],
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入用户名';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),
                    TextFormField(
                      controller: _passwordController,
                      obscureText: _obscurePassword,
                      decoration: InputDecoration(
                        labelText: '密码',
                        prefixIcon: const Icon(Icons.lock),
                        suffixIcon: IconButton(
                          icon: Icon(
                            _obscurePassword
                                ? Icons.visibility
                                : Icons.visibility_off,
                          ),
                          onPressed: () {
                            setState(() {
                              _obscurePassword = !_obscurePassword;
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        filled: true,
                        fillColor: Colors.grey[50],
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入密码';
                        }
                        if (value.length < 6) {
                          return '密码长度不能少于6位';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 32),
                    _isLoading
                        ? const CircularProgressIndicator()
                        : ElevatedButton(
                            onPressed: _submitForm,
                            style: ElevatedButton.styleFrom(
                              backgroundColor:
                                  const Color.fromARGB(255, 12, 113, 255),
                              padding: const EdgeInsets.symmetric(
                                vertical: 16,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              elevation: 5,
                            ),
                            child: const Text(
                              '登录',
                              style: TextStyle(
                                fontSize: 18,
                                color: Colors.white,
                              ),
                            ),
                          ),
                  ],
                ),
              ),
              const SizedBox(height: 40),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(
                    onPressed: () {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('忘记密码功能待实现')),
                      );
                    },
                    child: const Text(
                      '忘记密码?',
                      style: TextStyle(
                        color: Color.fromARGB(255, 12, 113, 255),
                      ),
                    ),
                  ),
                  const SizedBox(width: 20),
                  TextButton(
                    onPressed: () {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('注册功能待实现')),
                      );
                    },
                    child: const Text(
                      '新用户注册',
                      style: TextStyle(
                        color: Color.fromARGB(255, 12, 113, 255),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 主页
class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;

  static final List<Widget> _pages = [
    GeneratorPage(),
    LogsPage(),
    CameraPage(),
    DevicesPage(),
    SettingsPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_selectedIndex],
      extendBody: true,
      bottomNavigationBar: ClipRRect(
        borderRadius: const BorderRadius.vertical(
          top: Radius.circular(20),
        ),
        child: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          currentIndex: _selectedIndex,
          selectedItemColor: Theme.of(context).colorScheme.primary,
          unselectedItemColor: Colors.grey,
          showUnselectedLabels: true,
          backgroundColor: Colors.white,
          elevation: 10,
          onTap: (index) => setState(() => _selectedIndex = index),
          items: [
            BottomNavigationBarItem(
              icon: const Icon(Icons.home),
              label: '操作',
            ),
            BottomNavigationBarItem(
              icon: const Icon(Icons.list),
              label: '日志表',
            ),
            BottomNavigationBarItem(
              icon: Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.primary,
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 10,
                      offset: const Offset(0, 5),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.photo_camera,
                  color: Colors.white,
                ),
              ),
              label: '',
            ),
            BottomNavigationBarItem(
              icon: const Icon(Icons.device_hub),
              label: '设备库',
            ),
            BottomNavigationBarItem(
              icon: const Icon(Icons.person),
              label: '我的',
            ),
          ],
        ),
      ),
    );
  }
}

class GeneratorPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          const SizedBox(height: 100),
          Text(
            '智能星闪拣货系统',
            style: TextStyle(
              fontSize: 24,
              color: Colors.blue[800],
              shadows: [
                Shadow(
                  offset: const Offset(1.5, 1.5),
                  blurRadius: 3.0,
                  color: const Color.fromARGB(125, 0, 0, 0),
                ),
              ],
            ),
          ),
          const SizedBox(height: 40),
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ElevatedButton.icon(
                onPressed: () {
                  context.read<MyAppState>().startPicking();
                  Navigator.pushNamed(context, '/picking');
                },
                icon: const Icon(Icons.shopping_cart),
                label: const Text('拣货操作'),
              ),
              const SizedBox(height: 20),
              ElevatedButton.icon(
                onPressed: () {
                  context.read<MyAppState>().startRestocking();
                  Navigator.pushNamed(context, '/restocking');
                },
                icon: const Icon(Icons.refresh),
                label: const Text('补货操作'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class PickingPage extends StatefulWidget {
  const PickingPage({super.key});

  @override
  State<PickingPage> createState() => _PickingPageState();
}

class _PickingPageState extends State<PickingPage> {
  final _formKey = GlobalKey<FormState>();
  final _quantityController = TextEditingController();
  bool _isLoading = false;
  bool _isCreatingOrder = false;
  bool _isLoadingProducts = true; // 加载货物列表的状态
  List<Map<String, dynamic>> _addedItems = []; // 存储添加的货物
  List<dynamic> _historyOrders = []; // 历史订单
  List<dynamic> _productList = []; // 货物列表（从devices接口获取）
  String? _selectedProduct; // 当前选中的货物
  int _currentPage = 1;
  int _pageSize = 10;

  // 新增：控制显示表单还是订单详情
  bool _showOrderDetails = false;
  List<dynamic> _currentOrders = []; // 存储当前要显示的订单详情

  @override
  void initState() {
    super.initState();
    _fetchProducts(); // 初始化时获取货物列表
    _fetchHistoryOrders(); // 初始化时获取历史订单
  }

  @override
  void dispose() {
    _quantityController.dispose();
    super.dispose();
  }

  // 从devices接口获取货物列表（product字段）
  Future<void> _fetchProducts() async {
    setState(() => _isLoadingProducts = true);
    try {
      final appState = context.read<MyAppState>();
      if (appState.token == null) {
        throw Exception('未登录，请先登录');
      }
      // 构建带有分页参数的URL
      final queryParams = {
        'page': _currentPage.toString(),
        'page_size': _pageSize.toString(),
      };

      // 调用devices接口获取货物列表
      final response = await ApiService.post(
        'devices', // 接口端点
        appState.token!,
        data: queryParams,
      );

      if (response['status'] == 200) {
        setState(() {
          // 提取devices中的product字段作为货物列表
          _productList = response['data']['devices'] as List<dynamic>;
          _isLoadingProducts = false;
        });
      } else {
        throw Exception('获取货物列表失败: ${response['message']}');
      }
    } catch (e) {
      setState(() => _isLoadingProducts = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取货物列表失败: $e')),
      );
    }
  }

  // 添加货物到列表
  void _addItem() {
    if (_formKey.currentState!.validate() && _selectedProduct != null) {
      setState(() {
        _addedItems.add({
          'product': _selectedProduct!,
          'quantity': int.parse(_quantityController.text),
        });

        _quantityController.clear();
        _selectedProduct = null;
      });
    }
  }

  void _removeItem(int index) {
    setState(() => _addedItems.removeAt(index));
  }

  // 创建订单（合并所有添加的货物）
  Future<void> _createPickingOrder() async {
    if (_addedItems.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先添加货物')),
      );
      return;
    }

    setState(() => _isCreatingOrder = true);
    try {
      final appState = context.read<MyAppState>();
      final requestData = {
        'orders': _addedItems,
      };
      final response = await ApiService.post(
        'picking_product',
        appState.token!,
        data: requestData,
      );

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(response['message'] ?? '创建拣货订单成功')),
      );

      // 刷新历史订单并清空当前货物列表
      await _fetchHistoryOrders();
      setState(() {
        _addedItems.clear();
        _isCreatingOrder = false;
        // 切换到订单详情视图
        if (response['data'] != null && response['data'] is List) {
          _currentOrders = response['data'] as List<dynamic>;
          _showOrderDetails = true;
        }
      });
    } catch (e) {
      setState(() => _isCreatingOrder = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('创建拣货订单失败: $e')),
      );
    }
  }

  // 获取历史订单
  Future<void> _fetchHistoryOrders() async {
    try {
      final appState = context.read<MyAppState>();
      final response = await ApiService.post(
        'picking/history',
        appState.token!,
        data: {'page': _currentPage, 'page_size': _pageSize},
      );
      setState(() => _historyOrders = response['data']?['orders'] ?? []);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取历史订单失败: $e')),
      );
    }
  }

  // 显示历史订单详情
  void _showHistoryOrderDetail(Map<String, dynamic> order) {
    setState(() {
      _currentOrders = [order]; // 单个订单包装成列表
      _showOrderDetails = true;
    });
  }

  // 修改状态文本映射方法，支持bool和int类型
  String _getStatusText(dynamic status) {
    if (status is bool) {
      return status ? '已完成' : '待处理';
    } else if (status is int) {
      switch (status) {
        case 0:
          return '待处理';
        case 1:
          return '已完成';
        default:
          return '未知状态';
      }
    }
    return '未知状态';
  }

  Color getStatusColor(dynamic status) {
    if (status is bool) {
      return status ? Colors.green : Colors.orange;
    } else if (status is int) {
      return status == 1 ? Colors.green : Colors.orange;
    }
    return Colors.grey;
  }

  // 标记订单为已完成
  Future<void> _markAsCompleted(String orderNumber) async {
    try {
      final appState = Provider.of<MyAppState>(context, listen: false);
      if (appState.token == null) {
        throw Exception('未登录，请先登录');
      }

      final requestData = {
        'orders': [
          {'number': orderNumber}
        ]
      };
      final response = await ApiService.post(
        'picking/delete',
        appState.token!,
        data: requestData,
      );

      setState(() {
        for (var order in _currentOrders) {
          if (order['uuid'] == orderNumber && order['status'] == false) {
            order['status'] = true; // 更新状态
          }
          if (order['uuid'] == orderNumber && order['status'] == 0) {
            order['status'] = 1; // 更新状态
          }
        }
      });

      // ScaffoldMessenger.of(context).showSnackBar(
      //   SnackBar(content: Text('状态已更新为已完成')),
      // );
    } catch (e) {
      // ScaffoldMessenger.of(context).showSnackBar(
      //   SnackBar(content: Text('状态更新失败: $e')),
      // );
    }
  }

  // 返回表单视图
  void _backToForm() {
    setState(() {
      _showOrderDetails = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('拣货操作'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            context.read<MyAppState>().resetOperation();
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.history),
            onPressed: () => _showHistoryOrders(),
            tooltip: '历史订单',
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 根据状态显示表单或订单详情
            if (_showOrderDetails && _currentOrders.isNotEmpty)
              buildOrderDetails()
            else
              _buildFormContent(),
          ],
        ),
      ),
    );
  }

  // 构建订单详情视图
  Widget buildOrderDetails() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 返回按钮
        ElevatedButton(
          onPressed: _backToForm,
          child: const Text('返回拣货表单'),
        ),
        const SizedBox(height: 16),

        const Text(
          '订单详情',
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ),
        const Divider(height: 20),

        // 遍历所有订单
        for (var order in _currentOrders)
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 订单基本信息
              Text('订单编号: ${order['number']}'),
              Text('类型: ${order['type'] == 'S' ? '补货' : '未知'}'),
              Text(
                '状态: ${_getStatusText(order['status'])}',
                style: TextStyle(
                  color: getStatusColor(order['status']),
                ),
              ),
              // 货物详情
              const Text('货物信息:',
                  style: TextStyle(fontWeight: FontWeight.bold)),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 4),
                child: Text('• ${order['product']} x ${order['quantity']}'),
              ),

              // 订单分隔线（最后一个订单不需要）
              if (order != _currentOrders.last) const Divider(height: 20),

              // 操作按钮（仅待处理订单显示）
              if (order['status'] == false || order['status'] == 0)
                Padding(
                  padding: const EdgeInsets.only(top: 16),
                  child: ElevatedButton(
                    onPressed: () => _markAsCompleted(order['number']),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                    ),
                    child: const Text('标记为已完成'),
                  ),
                ),
            ],
          ),
      ],
    );
  }

  // 构建表单内容
  Widget _buildFormContent() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Icon(
          Icons.shopping_cart,
          size: 100,
          color: Colors.blue,
        ),
        const SizedBox(height: 20),
        const Text(
          '添加拣货货物',
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 30),

        // 输入表单（下拉选择框+数量输入）
        Form(
          key: _formKey,
          child: Column(
            children: [
              // 货物选择下拉框
              _isLoadingProducts
                  ? const CircularProgressIndicator() // 加载中
                  : _productList.isEmpty
                      ? const Text('暂无货物数据，请稍后重试')
                      : DropdownButtonFormField<String>(
                          value: _selectedProduct,
                          decoration: const InputDecoration(
                            labelText: '选择货物',
                            prefixIcon: Icon(Icons.production_quantity_limits),
                            border: OutlineInputBorder(),
                          ),
                          items: _productList.map((item) {
                            final productName = item['product'] as String;
                            return DropdownMenuItem<String>(
                              value: productName,
                              child: Text(productName),
                            );
                          }).toList(),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return '请选择货物';
                            }
                            return null;
                          },
                          onChanged: (value) {
                            setState(() => _selectedProduct = value);
                          },
                        ),
              const SizedBox(height: 16),
              // 数量输入框
              TextFormField(
                controller: _quantityController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '拣货数量',
                  prefixIcon: Icon(Icons.numbers),
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入拣货数量';
                  }
                  if (int.tryParse(value) == null || int.parse(value) <= 0) {
                    return '请输入有效的数量';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _isLoading || _isLoadingProducts ? null : _addItem,
                child: _isLoading
                    ? const CircularProgressIndicator(color: Colors.white)
                    : const Text('添加货物'),
              ),
            ],
          ),
        ),

        const SizedBox(height: 30),

        // 已添加的货物列表
        if (_addedItems.isNotEmpty)
          Container(
            width: double.infinity,
            margin: const EdgeInsets.only(bottom: 20),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '已添加的货物',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const Divider(height: 16),
                for (var i = 0; i < _addedItems.length; i++)
                  Container(
                    margin: const EdgeInsets.symmetric(vertical: 4),
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: const Color.fromARGB(0, 255, 255, 255),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('${_addedItems[i]['product']}'),
                              Text(
                                '数量: ${_addedItems[i]['quantity']}',
                                style: TextStyle(color: Colors.grey[600]),
                              ),
                            ],
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete, color: Colors.red),
                          onPressed: () => _removeItem(i),
                        ),
                      ],
                    ),
                  ),
                const Divider(height: 16),
                ElevatedButton(
                  onPressed: _isCreatingOrder ? null : _createPickingOrder,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 96, 186, 99),
                    minimumSize: const Size(double.infinity, 48),
                  ),
                  child: _isCreatingOrder
                      ? const CircularProgressIndicator(color: Colors.white)
                      : const Text('创建订单',
                          style: TextStyle(color: Colors.white)),
                ),
              ],
            ),
          )
        else
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 20),
            child: Text(
              '请添加货物到列表',
              style: TextStyle(color: Colors.grey),
            ),
          ),
      ],
    );
  }

  // 显示历史订单列表
  void _showHistoryOrders() async {
    await _fetchHistoryOrders();

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '历史订单',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const Divider(height: 20),
            if (_historyOrders.isEmpty)
              const Center(
                child: Padding(
                  padding: EdgeInsets.all(24),
                  child: Text('暂无历史订单'),
                ),
              )
            else
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: _historyOrders.length,
                  itemBuilder: (context, index) {
                    final order = _historyOrders[index];
                    return Card(
                      margin: const EdgeInsets.symmetric(vertical: 8),
                      child: ListTile(
                        title: Text('订单ID: ${order['id']}'),
                        subtitle: Text('创建时间: ${order['timestamp']}'),
                        trailing: Icon(
                          order['status'] == true
                              ? Icons.check_circle
                              : Icons.pending,
                          color: order['status'] == true
                              ? Colors.green
                              : Colors.orange,
                        ),
                        onTap: () {
                          Navigator.pop(context); // 关闭底部弹窗
                          _showHistoryOrderDetail(order); // 显示订单详情
                        },
                      ),
                    );
                  },
                ),
              ),
            const SizedBox(height: 16),
            Center(
              child: ElevatedButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class RestockingPage extends StatefulWidget {
  const RestockingPage({super.key});

  @override
  State<RestockingPage> createState() => _RestockingPageState();
}

class _RestockingPageState extends State<RestockingPage> {
  final _formKey = GlobalKey<FormState>();
  final _quantityController = TextEditingController();
  bool _isLoading = false;
  bool _isCreatingOrder = false;
  bool _isLoadingProducts = true;
  List<Map<String, dynamic>> _addedItems = []; // 存储添加的补货货物
  List<dynamic> _historyOrders = []; // 历史订单列表
  List<dynamic> _productList = []; // 货物选择列表
  String? _selectedProduct; // 当前选中的货物
  int _currentPage = 1;
  int _pageSize = 10;

  // 新增状态变量
  bool _showOrderDetails = false; // 控制是否显示订单详情
  List<dynamic> _currentOrders = []; // 当前订单数据

  @override
  void initState() {
    super.initState();
    _fetchProducts();
    _fetchHistoryOrders();
  }

  @override
  void dispose() {
    _quantityController.dispose();
    super.dispose();
  }

  // 从devices接口获取货物列表
  Future<void> _fetchProducts() async {
    setState(() => _isLoadingProducts = true);
    try {
      final appState = context.read<MyAppState>();
      if (appState.token == null) throw Exception('未登录，请先登录');

      final queryParams = {
        'page': _currentPage.toString(),
        'page_size': _pageSize.toString(),
      };

      final response = await ApiService.post(
        'devices',
        appState.token!,
        data: queryParams,
      );

      if (response['status'] == 200) {
        setState(() {
          _productList = response['data']['devices'] as List<dynamic>;
          _isLoadingProducts = false;
        });
      } else {
        throw Exception('获取货物列表失败: ${response['message']}');
      }
    } catch (e) {
      setState(() => _isLoadingProducts = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取货物列表失败: $e')),
      );
    }
  }

  // 添加货物到列表
  void _addItem() {
    if (_formKey.currentState!.validate() && _selectedProduct != null) {
      setState(() {
        _addedItems.add({
          'product': _selectedProduct!,
          'quantity': int.parse(_quantityController.text),
        });
        _quantityController.clear();
        _selectedProduct = null;
      });
    }
  }

  void _removeItem(int index) {
    setState(() => _addedItems.removeAt(index));
  }

  // 创建补货订单
  Future<void> _createRestockingOrder() async {
    if (_addedItems.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先添加补货货物')),
      );
      return;
    }

    setState(() => _isCreatingOrder = true);
    try {
      final appState = context.read<MyAppState>();
      final requestData = {'orders': _addedItems};
      final response = await ApiService.post(
        'supply_product',
        appState.token!,
        data: requestData,
      );

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(response['message'] ?? '创建补货订单成功')),
      );

      await _fetchHistoryOrders();
      setState(() {
        _addedItems.clear();
        _isCreatingOrder = false;
        // 存储订单数据并切换视图
        if (response['data'] != null && response['data'] is List) {
          _currentOrders = response['data'] as List<dynamic>;
          _showOrderDetails = true;
        }
      });
    } catch (e) {
      setState(() => _isCreatingOrder = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('创建订单失败: $e')),
      );
    }
  }

  // 获取历史订单
  Future<void> _fetchHistoryOrders() async {
    try {
      final appState = context.read<MyAppState>();
      final response = await ApiService.post(
        'supply/history',
        appState.token!,
        data: {'page': _currentPage, 'page_size': _pageSize},
      );
      setState(() => _historyOrders = response['data']?['orders'] ?? []);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取历史订单失败: $e')),
      );
    }
  }

  // 显示历史订单详情
  void _showHistoryOrderDetail(Map<String, dynamic> order) {
    setState(() {
      _currentOrders = [order]; // 单个订单包装成列表
      _showOrderDetails = true;
    });
  }

// 修改状态文本映射方法，支持bool和int类型
  String _getStatusText(dynamic status) {
    if (status is bool) {
      return status ? '已完成' : '待处理';
    } else if (status is int) {
      switch (status) {
        case 0:
          return '待处理';
        case 1:
          return '已完成';
        default:
          return '未知状态';
      }
    }
    return '未知状态';
  }

  Color getStatusColor(dynamic status) {
    if (status is bool) {
      return status ? Colors.green : Colors.orange;
    } else if (status is int) {
      return status == 1 ? Colors.green : Colors.orange;
    }
    return Colors.grey;
  }

  // 标记订单为已完成
  Future<void> _markAsCompleted(String uuid) async {
    // try {
    final appState = Provider.of<MyAppState>(context, listen: false);
    if (appState.token == null) throw Exception('未登录，请先登录');

    final response = await ApiService.post(
      'supply/delete',
      appState.token!,
      data: {
        'orders': [
          {'number': uuid}
        ]
      },
    );

    setState(() {
      for (var order in _currentOrders) {
        if (order['uuid'] == uuid && order['status'] == false) {
          order['status'] = true; // 更新状态
        }
        if (order['uuid'] == uuid && order['status'] == 0) {
          order['status'] = 1; // 更新状态
        }
      }
    });

    // ScaffoldMessenger.of(context).showSnackBar(
    //   SnackBar(content: Text('状态已更新为已完成')),
    // );
    // } catch (e) {
    //   // ScaffoldMessenger.of(context).showSnackBar(
    //   //   SnackBar(content: Text('状态更新失败: $e')),
    //   // );
    // }
  }

  // 返回表单视图
  void _backToForm() {
    setState(() {
      _showOrderDetails = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('补货操作'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.history),
            onPressed: () => _showHistoryOrders(),
            tooltip: '历史订单',
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 根据状态显示表单或订单详情
            if (_showOrderDetails && _currentOrders.isNotEmpty)
              buildOrderDetails()
            else
              buildFormContent(),
          ],
        ),
      ),
    );
  }

  // 构建订单详情视图
  Widget buildOrderDetails() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 返回按钮
        ElevatedButton(
          onPressed: _backToForm,
          child: const Text('返回补货表单'),
        ),
        const SizedBox(height: 16),

        const Text(
          '订单详情',
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ),
        const Divider(height: 20),

        // 遍历所有订单
        for (var order in _currentOrders)
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 订单基本信息
              Text('订单编号: ${order['number']}'),
              Text('类型: ${order['type'] == 'S' ? '补货' : '未知'}'),
              // 修改订单详情中的状态显示
              Text(
                '状态: ${_getStatusText(order['status'])}',
                style: TextStyle(
                  color: getStatusColor(order['status']),
                ),
              ),

              // 货物详情
              const Text('货物信息:',
                  style: TextStyle(fontWeight: FontWeight.bold)),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 4),
                child: Text('• ${order['product']} x ${order['quantity']}'),
              ),

              // 订单分隔线（最后一个订单不需要）
              if (order != _currentOrders.last) const Divider(height: 20),

              // 操作按钮（仅待处理订单显示）
              if (order['status'] == false || order['status'] == 0)
                Padding(
                  padding: const EdgeInsets.only(top: 16),
                  child: ElevatedButton(
                    onPressed: () => _markAsCompleted(order['number']),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                    ),
                    child: const Text('标记为已完成'),
                  ),
                ),
            ],
          ),
      ],
    );
  }

  // 构建表单内容
  Widget buildFormContent() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Icon(
          Icons.ring_volume,
          size: 100,
          color: Color.fromARGB(255, 0, 130, 22),
        ),
        const SizedBox(height: 20),
        const Text(
          '添加补货货物',
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 30),

        // 输入表单
        Form(
          key: _formKey,
          child: Column(
            children: [
              // 货物选择下拉框
              _isLoadingProducts
                  ? const CircularProgressIndicator()
                  : _productList.isEmpty
                      ? const Text('暂无货物数据，请稍后重试')
                      : DropdownButtonFormField<String>(
                          value: _selectedProduct,
                          decoration: const InputDecoration(
                            labelText: '选择货物',
                            prefixIcon: Icon(Icons.production_quantity_limits),
                            border: OutlineInputBorder(),
                          ),
                          items: _productList
                              .map((item) => DropdownMenuItem<String>(
                                    value: item['product'] as String,
                                    child: Text(item['product'] as String),
                                  ))
                              .toList(),
                          validator: (value) =>
                              value == null || value.isEmpty ? '请选择货物' : null,
                          onChanged: (value) =>
                              setState(() => _selectedProduct = value),
                        ),
              const SizedBox(height: 16),

              // 数量输入框
              TextFormField(
                controller: _quantityController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '补货数量',
                  prefixIcon: Icon(Icons.numbers),
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入补货数量';
                  }
                  if (int.tryParse(value) == null || int.parse(value) <= 0) {
                    return '请输入有效的数量';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),

              ElevatedButton(
                onPressed: _isLoadingProducts ? null : _addItem,
                child: const Text('添加货物'),
              ),
            ],
          ),
        ),

        const SizedBox(height: 30),

        // 已添加的补货货物列表
        if (_addedItems.isNotEmpty)
          Container(
            width: double.infinity,
            margin: const EdgeInsets.only(bottom: 20),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '已添加的补货货物',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const Divider(height: 16),
                for (var i = 0; i < _addedItems.length; i++)
                  Container(
                    margin: const EdgeInsets.symmetric(vertical: 4),
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: const Color.fromARGB(0, 250, 250, 250),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('${_addedItems[i]['product']}'),
                              Text(
                                '数量: ${_addedItems[i]['quantity']}',
                                style: TextStyle(color: Colors.grey[600]),
                              ),
                            ],
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete, color: Colors.red),
                          onPressed: () => _removeItem(i),
                        ),
                      ],
                    ),
                  ),
                const Divider(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('开始补货流程...')),
                        );
                      },
                      child: const Text('开始补货'),
                    ),
                    ElevatedButton(
                      onPressed:
                          _isCreatingOrder ? null : _createRestockingOrder,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                      ),
                      child: _isCreatingOrder
                          ? const CircularProgressIndicator(color: Colors.white)
                          : const Text('创建补货订单'),
                    ),
                  ],
                ),
              ],
            ),
          )
        else
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 20),
            child: Text(
              '请添加补货货物到列表',
              style: TextStyle(color: Colors.grey),
            ),
          ),
      ],
    );
  }

  // 显示历史订单列表
  void _showHistoryOrders() async {
    await _fetchHistoryOrders();

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '历史订单',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const Divider(height: 20),
            if (_historyOrders.isEmpty)
              const Center(
                child: Padding(
                  padding: EdgeInsets.all(24),
                  child: Text('暂无历史订单'),
                ),
              )
            else
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: _historyOrders.length,
                  itemBuilder: (context, index) {
                    final order = _historyOrders[index];
                    return Card(
                      margin: const EdgeInsets.symmetric(vertical: 8),
                      child: ListTile(
                        title: Text('订单ID: ${order['id']}'),
                        subtitle: Text('创建时间: ${order['timestamp']}'),
                        trailing: Icon(
                          order['status'] == true
                              ? Icons.check_circle
                              : Icons.pending,
                          color: order['status'] == true
                              ? Colors.green
                              : Colors.orange,
                        ),
                        onTap: () {
                          Navigator.pop(context); // 关闭底部弹窗
                          _showHistoryOrderDetail(order); // 显示订单详情
                        },
                      ),
                    );
                  },
                ),
              ),
            const SizedBox(height: 16),
            Center(
              child: ElevatedButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class LogsPage extends StatefulWidget {
  @override
  _LogsPageState createState() => _LogsPageState();
}

class _LogsPageState extends State<LogsPage> {
  int _currentPage = 1;
  int _pageSize = 10; // 每页显示10条记录
  int _totalPages = 1;
  List<dynamic> _logs = [];
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _fetchLogs();
  }

  Future<void> _fetchLogs() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final appState = Provider.of<MyAppState>(context, listen: false);
      if (appState.token == null) {
        throw Exception('未登录，请先登录');
      }

      // 构建带有分页参数的URL
      final queryParams = {
        'page': _currentPage.toString(),
        'page_size': _pageSize.toString(),
      };
      final queryString = Uri(queryParameters: queryParams).query;

      // 调用API获取日志数据，携带page和pageSize参数
      final result = await ApiService.post(
        'logs?$queryString',
        appState.token!,
        data: queryParams,
      );

      setState(() {
        _logs = result['data']?['logs'] as List<dynamic>? ?? [];
        _totalPages = result['data']?['total_pages'] as int? ?? 1;
        _currentPage = result['data']?['current_page'] as int? ?? 1;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  void _handlePageChange(int newPage) {
    if (newPage >= 1 && newPage <= _totalPages && newPage != _currentPage) {
      setState(() {
        _currentPage = newPage;
      });
      _fetchLogs();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('操作日志表'),
        centerTitle: true,
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('出错了: $_errorMessage'),
            ElevatedButton(
              onPressed: _fetchLogs,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_logs.isEmpty) {
      return const Center(child: Text('暂无操作日志记录'));
    }

    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: _logs.length,
            itemBuilder: (context, index) {
              final log = _logs[index];
              return _buildLogItem(log);
            },
          ),
        ),
        _buildPaginationControls(),
      ],
    );
  }

  Widget _buildLogItem(Map<String, dynamic> log) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '操作类型: ${log['description']}',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  'ID: ${log['id']}',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text('订单编号: ${log['order_number']}'),
            const SizedBox(height: 4),
            Text('操作人: ${log['username']}'),
          ],
        ),
      ),
    );
  }

  Widget _buildPaginationControls() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
            onPressed: _currentPage > 1
                ? () => _handlePageChange(_currentPage - 1)
                : null,
            icon: const Icon(Icons.arrow_left),
            disabledColor: Colors.grey[300],
          ),
          Text('第 $_currentPage 页 / 共 $_totalPages 页'),
          IconButton(
            onPressed: _currentPage < _totalPages
                ? () => _handlePageChange(_currentPage + 1)
                : null,
            icon: const Icon(Icons.arrow_right),
            disabledColor: Colors.grey[300],
          ),
        ],
      ),
    );
  }
}

class CameraPage extends StatefulWidget {
  const CameraPage({super.key});

  @override
  State<CameraPage> createState() => _CameraPageState();
}

class _CameraPageState extends State<CameraPage> {
  final _formKey = GlobalKey<FormState>();
  final _macController = TextEditingController();
  bool _isVerifying = false;

  // 验证MAC地址并请求接口
  Future<void> _verifyMacAddress() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isVerifying = true;
      });

      try {
        // 获取MAC地址
        String macAddress = _macController.text.trim();

        // 显示加载提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('正在验证设备信息...')),
        );

        // 获取token
        final appState = Provider.of<MyAppState>(context, listen: false);
        if (appState.token == null) {
          throw Exception('请先登录');
        }

        // 调用接口验证设备
        final response = await ApiService.get(
          'devices?mac=$macAddress',
          appState.token!,
        );

        // 解析接口返回结果
        if (response['status'] == 200 && response['data'] != null) {
          bool isNew = response['data']['is_new'] ?? false;

          // 根据is_new跳转到不同页面
          if (isNew) {
            // 新设备，进入登记界面
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => RegisterGoodsPage(macAddress: macAddress),
              ),
            );
          } else {
            // 旧设备，进入修改界面
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ModifyDataPage(
                  macAddress: macAddress,
                  deviceData: response['data'],
                ),
              ),
            );
          }
        } else {
          throw Exception(response['message'] ?? '验证设备失败');
        }
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('验证失败: $e')),
        );
      } finally {
        setState(() {
          _isVerifying = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('设备验证'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            // 设备图标
            const Icon(
              Icons.device_hub,
              size: 120,
              color: Color.fromARGB(255, 12, 113, 255),
            ),
            const SizedBox(height: 40),

            // MAC地址输入表单
            Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    controller: _macController,
                    decoration: InputDecoration(
                      labelText: 'MAC地址',
                      hintText: '请输入设备MAC地址',
                      prefixIcon: const Icon(Icons.wifi),
                      border: const OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(12)),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 14,
                      ),
                    ),
                    keyboardType: TextInputType.text,
                    textCapitalization: TextCapitalization.none,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入MAC地址';
                      }
                    },
                  ),
                  const SizedBox(height: 30),

                  // 验证按钮
                  ElevatedButton.icon(
                    onPressed: _isVerifying ? null : _verifyMacAddress,
                    icon: _isVerifying
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(
                              color: Colors.white,
                              strokeWidth: 2,
                            ),
                          )
                        : const Icon(Icons.check_circle),
                    label: const Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 24,
                        vertical: 16,
                      ),
                      child: Text(
                        '验证设备',
                        style: TextStyle(fontSize: 18),
                      ),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 12, 113, 255),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      minimumSize: const Size(double.infinity, 0),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 40),

            // 说明文本
            const Text(
              '请输入设备MAC地址进行验证，系统将自动判断设备状态并进入对应操作界面',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}

// 设备登记界面
class RegisterGoodsPage extends StatefulWidget {
  final String macAddress;

  const RegisterGoodsPage({
    super.key,
    required this.macAddress,
  });

  @override
  State<RegisterGoodsPage> createState() => _RegisterGoodsPageState();
}

class _RegisterGoodsPageState extends State<RegisterGoodsPage> {
  final _formKey = GlobalKey<FormState>();
  final _productController = TextEditingController();
  final _quantityController = TextEditingController();
  bool _isSubmitting = false;

  @override
  void initState() {
    super.initState();
    // 设置默认值
    _quantityController.text = '1';
  }

  // 提交设备登记信息
  Future<void> _submitRegistration() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isSubmitting = true;
      });

      try {
        final appState = Provider.of<MyAppState>(context, listen: false);
        if (appState.token == null) {
          throw Exception('请先登录');
        }

        final String macAddress = widget.macAddress;
        final requestData = {
          'product': _productController.text.trim(),
          'quantity': int.parse(_quantityController.text.trim()),
        };

        final String endpoint = 'device/add?mac=$macAddress';

        final response = await ApiService.post(
          endpoint,
          appState.token!,
          data: requestData,
        );

        // 处理成功响应
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response['message'] ?? '设备登记成功')),
        );

        // 返回上一页
        Navigator.pop(context);
      } catch (e) {
        // ScaffoldMessenger.of(context).showSnackBar(
        //   SnackBar(content: Text('登记失败: $e')),
        // );
      } finally {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('设备登记'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '设备信息',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 16),

              // MAC地址显示（不可编辑）
              TextFormField(
                initialValue: widget.macAddress,
                decoration: const InputDecoration(
                  labelText: 'MAC地址',
                  border: OutlineInputBorder(),
                ),
                readOnly: true,
              ),
              const SizedBox(height: 16),

              // 设备名称
              TextFormField(
                controller: _productController,
                decoration: const InputDecoration(
                  labelText: '设备名称',
                  border: OutlineInputBorder(),
                  hintText: '请输入设备名称',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入设备名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 设备数量
              TextFormField(
                controller: _quantityController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '设备数量',
                  border: OutlineInputBorder(),
                  hintText: '请输入设备数量',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入设备数量';
                  }
                  if (int.tryParse(value) == null || int.parse(value) <= 0) {
                    return '请输入有效的数量';
                  }
                  return null;
                },
              ),

              const SizedBox(height: 32),

              // 提交按钮
              ElevatedButton(
                onPressed: _isSubmitting ? null : _submitRegistration,
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size(double.infinity, 50),
                  backgroundColor: const Color.fromARGB(255, 12, 113, 255),
                ),
                child: _isSubmitting
                    ? const CircularProgressIndicator(color: Colors.white)
                    : const Text(
                        '完成登记',
                        style: TextStyle(fontSize: 18),
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 设备信息修改界面
class ModifyDataPage extends StatefulWidget {
  final String macAddress;
  final Map<String, dynamic> deviceData;

  const ModifyDataPage({
    super.key,
    required this.macAddress,
    required this.deviceData,
  });

  @override
  State<ModifyDataPage> createState() => _ModifyDataPageState();
}

class _ModifyDataPageState extends State<ModifyDataPage> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _productController;
  late TextEditingController _quantityController;
  bool _isSubmitting = false;

  @override
  void initState() {
    super.initState();
    // 初始化表单数据
    _productController = TextEditingController(
      text: widget.deviceData['product']?.toString() ?? '',
    );
    _quantityController = TextEditingController(
      text: widget.deviceData['quantity']?.toString() ?? '',
    );
  }

  @override
  void dispose() {
    _productController.dispose();
    _quantityController.dispose();
    super.dispose();
  }

  // 提交修改
  Future<void> _submitModification() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isSubmitting = true;
      });

      try {
        final appState = Provider.of<MyAppState>(context, listen: false);
        if (appState.token == null) {
          throw Exception('请先登录');
        }
        final String macAddress = widget.macAddress;

        // 准备提交的数据
        final requestData = {
          'product': _productController.text.trim(),
          'quantity': int.parse(_quantityController.text.trim()),
        };
        final String endpoint = 'device/add?mac=$macAddress';

        // 调用修改接口
        final response = await ApiService.post(
          endpoint,
          appState.token!,
          data: requestData,
        );

        // 处理成功响应
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response['message'] ?? '设备信息修改成功')),
        );

        // 返回上一页
        Navigator.pop(context);
      } catch (e) {
        // ScaffoldMessenger.of(context).showSnackBar(
        //   SnackBar(content: Text('修改失败: $e')),
        // );
      } finally {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('修改设备信息'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '设备信息',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 16),

              // MAC地址显示（不可编辑）
              TextFormField(
                initialValue: widget.macAddress,
                decoration: const InputDecoration(
                  labelText: 'MAC地址',
                  border: OutlineInputBorder(),
                ),
                readOnly: true,
              ),
              const SizedBox(height: 16),

              // 设备名称
              TextFormField(
                controller: _productController,
                decoration: const InputDecoration(
                  labelText: '设备名称',
                  border: OutlineInputBorder(),
                  hintText: '请输入设备名称',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入设备名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 设备数量
              TextFormField(
                controller: _quantityController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '设备数量',
                  border: OutlineInputBorder(),
                  hintText: '请输入设备数量',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入设备数量';
                  }
                  if (int.tryParse(value) == null || int.parse(value) <= 0) {
                    return '请输入有效的数量';
                  }
                  return null;
                },
              ),

              const SizedBox(height: 32),

              // 提交按钮
              ElevatedButton(
                onPressed: _isSubmitting ? null : _submitModification,
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size(double.infinity, 50),
                  backgroundColor: const Color.fromARGB(255, 12, 113, 255),
                ),
                child: _isSubmitting
                    ? const CircularProgressIndicator(color: Colors.white)
                    : const Text(
                        '保存修改',
                        style: TextStyle(fontSize: 18),
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class DevicesPage extends StatefulWidget {
  @override
  _DevicesPageState createState() => _DevicesPageState();
}

class _DevicesPageState extends State<DevicesPage> {
  int _currentPage = 1;
  int _pageSize = 10; // 每页显示10条记录
  int _totalPages = 1;
  List<dynamic> _devices = [];
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _fetchDevices();
  }

  Future<void> _fetchDevices() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final appState = Provider.of<MyAppState>(context, listen: false);
      if (appState.token == null) {
        throw Exception('未登录，请先登录');
      }

      // 构建带有分页参数的URL
      final queryParams = {
        'page': _currentPage.toString(),
        'page_size': _pageSize.toString(),
      };
      final queryString = Uri(queryParameters: queryParams).query;

      // 调用API获取日志数据，携带page和pageSize参数
      final result = await ApiService.post(
        'devices?$queryString',
        appState.token!,
        data: queryParams,
      );

      setState(() {
        _devices = result['data']?['devices'] as List<dynamic>? ?? [];
        _totalPages = result['data']?['total_pages'] as int? ?? 1;
        _currentPage = result['data']?['current_page'] as int? ?? 1;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  void _handlePageChange(int newPage) {
    if (newPage >= 1 && newPage <= _totalPages && newPage != _currentPage) {
      setState(() {
        _currentPage = newPage;
      });
      _fetchDevices();
    }
  }

  // 复制MAC地址到剪贴板
  Future<void> _copyMacAddress(String macAddress) async {
    await Clipboard.setData(ClipboardData(text: macAddress));

    // 显示复制成功提示
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('MAC地址已复制到剪贴板')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('设备列表'),
        centerTitle: true,
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('出错了: $_errorMessage'),
            ElevatedButton(
              onPressed: _fetchDevices,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_devices.isEmpty) {
      return const Center(child: Text('暂无设备'));
    }

    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: _devices.length,
            itemBuilder: (context, index) {
              final device = _devices[index];
              return _buildDeviceItem(device);
            },
          ),
        ),
        _buildPaginationControls(),
      ],
    );
  }

  Widget _buildDeviceItem(Map<String, dynamic> device) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '设备类型: ${device['product']}',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  'ID: ${device['id']}',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text('设备数量: ${device['quantity']}'),
            const SizedBox(height: 4),

            // 带复制按钮的MAC地址行
            Row(
              children: [
                Text('MAC地址: ${device['mac_address']}'),
                const SizedBox(width: 8),
                IconButton(
                  icon: const Icon(Icons.copy, size: 18),
                  onPressed: () => _copyMacAddress(device['mac_address']),
                  tooltip: '复制MAC地址',
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPaginationControls() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
            onPressed: _currentPage > 1
                ? () => _handlePageChange(_currentPage - 1)
                : null,
            icon: const Icon(Icons.arrow_left),
            disabledColor: Colors.grey[300],
          ),
          Text('第 $_currentPage 页 / 共 $_totalPages 页'),
          IconButton(
            onPressed: _currentPage < _totalPages
                ? () => _handlePageChange(_currentPage + 1)
                : null,
            icon: const Icon(Icons.arrow_right),
            disabledColor: Colors.grey[300],
          ),
        ],
      ),
    );
  }
}

class SettingsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var appState = context.watch<MyAppState>();

    return ListView(
      children: [
        if (appState.isLoggedIn)
          UserAccountsDrawerHeader(
            accountName: Text(appState.username ?? '用户'),
            accountEmail: const Text('拣货系统操作员'),
            currentAccountPicture: const CircleAvatar(
              child: Icon(Icons.person),
            ),
          ),
        ListTile(
          leading: const Icon(Icons.settings),
          title: const Text('系统设置'),
          onTap: () {
            // 处理设置逻辑
          },
        ),
        ListTile(
          leading: const Icon(Icons.help),
          title: const Text('帮助中心'),
          onTap: () {
            // 处理帮助逻辑
          },
        ),
        if (appState.isLoggedIn)
          ListTile(
            leading: const Icon(Icons.logout),
            title: const Text('退出登录'),
            textColor: Colors.red,
            onTap: () {
              appState.logout();
              Navigator.pushReplacementNamed(context, '/login');
            },
          ),
      ],
    );
  }
}
